/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yaps.petstore.mdp.print;

import com.yaps.petstore.entity.order.Order;
import com.yaps.petstore.entity.order.OrderLine;
import com.yaps.petstore.util.Constants;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

/**
 *
 * @author neila
 */
public class OrderPrinterBean implements MessageListener{
    
    
    private final String cname = this.getClass().getName();
    private Logger logger = Logger.getLogger(Constants.LOGGER_MDP);

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


    @Override
    public void onMessage(Message message) {
        final String mname = "onMessage";
        logger.entering(cname, mname);
        try {
            if (message instanceof ObjectMessage) {
                ObjectMessage msg = (ObjectMessage) message;
                logger.info("Message received! Id=" + msg.getJMSMessageID());
                Order order = (Order) msg.getObject();
                printOrder(order);
            } else {
                logger.warning("Message of wrong type: Id=" + message.getJMSMessageID() + " class=" + message.getClass().getName());
            }
        } catch (JMSException e) {
            logger.throwing(cname, mname, e);
            
        }
        logger.exiting(cname, mname);
    }
    
    private void printOrder(Order order) {
        logger.info("Order # " + order.getId() + " on the " + dateFormat.format(order.getOrderDate()));
        logger.info(order.getCustomer().getFirstname() + order.getCustomer().getLastname() + " bought ");

        for (OrderLine line : order.getOrderLines()) {
            logger.info("\t" + line.getItem().getName() + "*" + line.getQuantity() + "=" + line.getSubTotal());
        }
        logger.info("Total=" + order.getTotal());
    }
    
}
